package com.example.controller;

import com.example.dto.Result;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Part;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;

@Controller
@RequestMapping("/files")
public class FileUploadController {

    /*@PostMapping
    @ResponseBody
    public String upload(@RequestPart byte[] file){
        File target = new File("D:\\dev\\appserver\\apache-tomcat-9.0.44\\upload\\test.jpg");
        try (FileOutputStream out = new FileOutputStream(target)){
            out.write(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Result.ok();";
    }*/

    /*@PostMapping
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        if(file.isEmpty())
            return "文件为空！";
        File dest = new File("/Users/qinruihua/Downloads/xxxxxxx.jpg");
        file.transferTo(dest);
        return "上传成功";
    }*/

    @PostMapping
    @ResponseBody
    public String upload(@RequestPart Part file){

        File dest = new File("/Users/qinruihua/Downloads/xxxxxxx.jpg");
        try {
            System.out.println("文件名："+ file.getSubmittedFileName());
            FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(dest));
        } catch (IOException e) {
            return "上传失败";
        }
        return "上传成功";
    }

    @GetMapping
    @ResponseBody
    public Result get(){
        return Result.fail();
    }
}
